package cn.mw.cmdb.timeplan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.mw.cmdb.mongoMapper.MwTimePlanRelationModuleMapper;
import cn.mw.cmdb.timeplan.entity.MwTimePlanRelationModuleDto;
import cn.mw.cmdb.timeplan.param.MwTimePlanParam;
import cn.mw.cmdb.timeplan.service.MwTimePlanService;
import cn.mw.components.mongodb.entity.SearchParam;
import cn.mw.components.mongodb.tool.CriteriaWrapper;
import cn.mw.microMonitorCommon.api.cmdb.MwTimePlanCommonApi;
import cn.mw.microMonitorCommon.api.common.ResponseBase;
import cn.mw.microMonitorCommon.api.powerjob.PowerJobRequestParam;
import cn.mw.microMonitorCommon.api.powerjob.PowerJobService;
import cn.mw.microMonitorCommon.entity.cmdb.TimePlanCommonDto;
import cn.mw.microMonitorCommon.param.MwTimePlanparam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gengjb
 * @description 时间计划通用API
 */
@DubboService
@Slf4j
@Service
public class MwTimePlanCommonImpl implements MwTimePlanCommonApi {

    @DubboReference(check = false,timeout = 12000)
    private PowerJobService powerJobService;

    private MwTimePlanService timePlanService;

    private MwTimePlanRelationModuleMapper planRelationModuleMapper;

    private final String CORN = "CRON";

    @Autowired
    public MwTimePlanCommonImpl(MwTimePlanService timePlanService,MwTimePlanRelationModuleMapper planRelationModuleMapper) {
        this.timePlanService = timePlanService;
        this.planRelationModuleMapper = planRelationModuleMapper;
    }

    @Override
    public void generatePowerJob(MwTimePlanparam timePlanparam) throws Exception {
        //根据时间计划ID获取时间计划的corn表达式
        MwTimePlanParam param = new MwTimePlanParam();
        param.setId(timePlanparam.getTimePlanId());
        MwTimePlanParam planParam = timePlanService.select(param);
        if(planParam == null){
            return;
        }
        //根据数据ID获取原先的任务并删除
        deleteTimePlanRelationInfo(timePlanparam.getTypeId());
        //生成任务
        List<PowerJobRequestParam> jobRequestParams = new ArrayList<>();
        for (String cron : planParam.getCrons()) {
            PowerJobRequestParam jobRequestParam = new PowerJobRequestParam();
            BeanUtil.copyProperties(timePlanparam, jobRequestParam, CopyOptions.create().setIgnoreNullValue(true));
            //设置为corn表达式格式
            jobRequestParam.setTimeExpressionType(CORN);
            jobRequestParam.setTimeExpression(cron);
            jobRequestParams.add(jobRequestParam);
        }
        ResponseBase<List<Long>> responseBase = powerJobService.batchSaveOrUpdateJob(jobRequestParams);
        List<Long> taskIds = responseBase.getData();
        if(CollectionUtils.isEmpty(taskIds)){
            log.info("任务生成失败:jobRequestParams>>>"+jobRequestParams);
            return;
        }
        List<MwTimePlanRelationModuleDto> moduleDtos = new ArrayList<>();
        for (Long taskId : taskIds) {
            MwTimePlanRelationModuleDto mwTimePlanRelevenceModuleDto = new MwTimePlanRelationModuleDto();
            mwTimePlanRelevenceModuleDto.setTimePlanId(timePlanparam.getTimePlanId());
            mwTimePlanRelevenceModuleDto.setModuleName(timePlanparam.getModuleName());
            mwTimePlanRelevenceModuleDto.setTaskId(taskId);
            mwTimePlanRelevenceModuleDto.setTypeId(timePlanparam.getTypeId());
            mwTimePlanRelevenceModuleDto.setTaskDescription(timePlanparam.getJobDescription());
            moduleDtos.add(mwTimePlanRelevenceModuleDto);
        }
        //将数据添加到关联信息表
        planRelationModuleMapper.insert(moduleDtos);
    }

    @Override
    public void deleteTimePlanRelationInfo(String typeId) throws Exception {
        //根据模块数据ID获取到关联的定时任务ID
        Query query = new Query(CriteriaWrapper.where(MwTimePlanRelationModuleDto::getTypeId).is(typeId));
        List<MwTimePlanRelationModuleDto> moduleDtos = planRelationModuleMapper.find(query);
        if(CollectionUtils.isEmpty(moduleDtos)){return;}
        List<Long> taskIds = moduleDtos.stream().filter(s->s != null).map(s -> s.getTaskId()).collect(Collectors.toList());
        log.info("deleteTimePlanRelationInfo() taskIds>>>"+taskIds);
        if(!CollectionUtils.isEmpty(taskIds)){
            //删除任务
            powerJobService.deleteJob(taskIds);
        }
        //删除关联关系
        planRelationModuleMapper.remove(query);
    }

    @Override
    public List<TimePlanCommonDto> getTimePlanDropDown() throws Exception {
        List<TimePlanCommonDto> timePlanCommonDtos = new ArrayList<>();
        List<MwTimePlanParam> datas = timePlanService.list(new SearchParam());
        if(CollectionUtils.isEmpty(datas)){
            return timePlanCommonDtos;
        }
        for (MwTimePlanParam planParam : datas) {
            TimePlanCommonDto timePlanCommonDto = new TimePlanCommonDto();
            timePlanCommonDto.setTimePlanId(planParam.getId());
            timePlanCommonDto.setTimePlanName(planParam.getName());
            timePlanCommonDtos.add(timePlanCommonDto);
        }
        return timePlanCommonDtos;
    }


}
